package com.jstyle.jclife.activity;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclife.R;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.TipsDialog;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class BreathStartActivity extends BaseActivity {
    private static final String TAG = "BreathStartActivity";
    @BindView(R.id.iv_breath_off)
    ImageView ivBreathOff;
    @BindView(R.id.iv_breath_setting)
    ImageView ivBreathSetting;
    @BindView(R.id.iv_breath_bg)
    ImageView ivBreathBg;
    @BindView(R.id.bt_breath_start)
    Button btBreathStart;
    @BindView(R.id.iv_breath_anim)
    ImageView ivBreathAnim;
    @BindView(R.id.tv_countTimer)
    TextView tvCountTimer;
    @BindView(R.id.tv_prepare)
    TextView tvPrepare;
    @BindView(R.id.tv_breath_level)
    TextView tvBreathLevel;
    @BindView(R.id.tv_prepare_countDown)
    TextView tvPrepareCountDown;
    @BindView(R.id.iv_breath_hr)
    ImageView idBreathHr;
    @BindView(R.id.tv_breath_hrvalue)
    TextView tvBreathHrvalue;
    @BindView(R.id.tv_hr_label)
    TextView tvHrLabel;
    private boolean startMeasure;
    private AnimationDrawable animationDrawable;
    private int dely;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_breath_srart);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_breath_off, R.id.iv_breath_setting, R.id.bt_breath_start})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_breath_off:
                if (!isFinish) {
                    showTipsDialog();
                } else {
                    finish();
                }

                break;
            case R.id.iv_breath_setting:
                startActivity(BreathSettingActivity.class);
                break;
            case R.id.bt_breath_start:
                startBreath();
                break;
        }
    }

    float scaleValue = 3.6f;
    float startValue = 0.5f;

    private void startBreath() {
        final int duration = SharedPreferenceUtils.getInteger(BreathSettingActivity.KEY_DURATION, 1);
        if (duration == 0) {
            ScreenUtils.showSetSuccessFul(ivBreathAnim, getString(R.string.Please_set_the_time_first));
            return;
        }
        startMeasure = !startMeasure;
        tvPrepare.setVisibility(View.VISIBLE);
        tvPrepareCountDown.setVisibility(View.VISIBLE);
        btBreathStart.setVisibility(View.GONE);

        Observable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposablePrepare = d;
            }

            @Override
            public void onNext(Long aLong) {
                tvPrepareCountDown.setText(String.valueOf(3 - aLong));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                isFinish = false;
                tvBreathLevel.setVisibility(View.VISIBLE);
                tvBreathLevel.setText(R.string.Get_Ready);
                tvPrepare.setVisibility(View.GONE);
                tvPrepareCountDown.setVisibility(View.GONE);
                ivBreathAnim.setVisibility(View.VISIBLE);
                enableMode(true);
                startPreAnim(duration);
            }
        });
        //  ivBreathAnim.setVisibility(startMeasure ? View.VISIBLE : View.INVISIBLE);
//        if (startMeasure) {
//
//        } else {
//            ivBreathAnim.clearAnimation();
//        }
    }

    private void startPreAnim(final int duration) {
        final ScaleAnimation scaleAnimation = new ScaleAnimation(startValue, scaleValue, startValue, scaleValue, ivBreathAnim.getWidth() / 2f, ivBreathAnim.getHeight() / 2f);
        scaleAnimation.setDuration(2000);
        scaleAnimation.setRepeatMode(Animation.REVERSE);
        scaleAnimation.setRepeatCount(5);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                startPractice();
                startTimer(duration);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ivBreathAnim.startAnimation(scaleAnimation);
    }

    private void startPractice() {
        int level = SharedPreferenceUtils.getInteger(BreathSettingActivity.KEY_level, 1);
        int duration1 = 4000;
        int duration2 = 4000;
        dely = 0;
        if (level == 2) {
            duration1 = 5500;
            duration2 = 4000;
        } else if (level == 3) {
            duration1 = 2500;
            duration2 = 5000;
            dely = 2500;
        }
        //呼气
        final ScaleAnimation scaleAnimationExhale = new ScaleAnimation(startValue, scaleValue, startValue, scaleValue, ivBreathAnim.getWidth() / 2f, ivBreathAnim.getHeight() / 2f);
        scaleAnimationExhale.setDuration(duration1);
        //吸气
        final ScaleAnimation scaleAnimationInhale = new ScaleAnimation(scaleValue, startValue, scaleValue, startValue, ivBreathAnim.getWidth() / 2f, ivBreathAnim.getHeight() / 2f);
        scaleAnimationInhale.setDuration(duration2);
        scaleAnimationInhale.setStartOffset(dely);
        scaleAnimationExhale.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                tvBreathLevel.setText(getString(R.string.inhale));
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (!isFinish) {
                    Log.i(TAG, "onAnimationenf: ");
                    tvBreathLevel.setText(R.string.hold_breath);
                    ivBreathAnim.startAnimation(scaleAnimationInhale);
                }

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


        //设置动画的重复模式：反转REVERSE和重新开始RESTART

        scaleAnimationInhale.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                Log.i(TAG, "onAnimationStart: ");
                tvBreathLevel.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isDestroyed())
                            tvBreathLevel.setText(getString(R.string.exhale));
                    }
                }, dely);

            }

            @Override
            public void onAnimationEnd(Animation animation) {

                if (!isFinish) {
                    ivBreathAnim.startAnimation(scaleAnimationExhale);

                }

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


        ivBreathAnim.startAnimation(scaleAnimationExhale);
    }

    Disposable disposable;
    Disposable disposablePrepare;
    boolean isFinish = true;

    private void startTimer(int duration) {
        tvCountTimer.setVisibility(View.VISIBLE);
        final long count = duration * 60;
        Observable.intervalRange(0, count + 1, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(Long aLong) {
                if (aLong == 0) {
                    tvBreathHrvalue.setVisibility(View.VISIBLE);
                    tvHrLabel.setVisibility(View.VISIBLE);
                    idBreathHr.setVisibility(View.VISIBLE);
                    tvBreathLevel.setText("GO");
                } else {
                    tvCountTimer.setText(DateUtil.getSportAxieTime((int) (count - aLong)));
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Complete();
                enableMode(false);
            }
        });
    }

    private void Complete() {
        isFinish = true;
        btBreathStart.setVisibility(View.VISIBLE);
        tvBreathHrvalue.setVisibility(View.INVISIBLE);
        tvHrLabel.setVisibility(View.INVISIBLE);
        idBreathHr.setVisibility(View.INVISIBLE);
        tvCountTimer.setVisibility(View.GONE);
        tvBreathLevel.setVisibility(View.GONE);
        ivBreathAnim.clearAnimation();
        ivBreathAnim.setVisibility(View.GONE);
    }

    private void showTipsDialog() {
        TipsDialog tipsDialog = new TipsDialog(this, R.style.jstyleDialog_style);
        tipsDialog.setTitle(getString(R.string.Attention));
        tipsDialog.setContent(getString(R.string.Attention_breath_tips));
        tipsDialog.setConfimText(getString(R.string.ok));
        tipsDialog.setTipsConfimListener(new TipsDialog.TipsConfimListener() {
            @Override
            public void onConfim() {
                enableMode(false);
                finish();
            }
        });
        tipsDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(disposable);
        unSubscribe(disposablePrepare);

    }

    private void enableMode(boolean enable) {
        ExerciseMode exerciseMode = new ExerciseMode();
        exerciseMode.setEnableStatus(enable ? ExerciseMode.Status_START : ExerciseMode.Status_FINISH);
        exerciseMode.setExerciseMode(ExerciseMode.Mode_BREATH);
        sendData(SendCmdState.Set_EXERCISE_MODE, exerciseMode);
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case ACTIVITY_EXERCISE_DATA:
                String heart = maps.get(DeviceKey.KExerciseHeart);
                if (Integer.valueOf(heart) == 255) {
                    unSubscribe(disposable);
                    Complete();
                } else {
                    tvBreathHrvalue.setText(heart);
                }

                break;
        }
    }
}
